package test.http.core.controller;

import blue.http.core.annotation.Http;
import blue.http.core.annotation.HttpMethod;
import blue.http.core.annotation.Multipart;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.UploadFile;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @author Jin Zheng
 * @since 1.0 2020-10-29
 */
@Controller
@Http(url = "/upload", method = HttpMethod.POST)
public class UploadController {
	public UploadController() {
	}

	public void index(HttpRequest request) {
		System.out.println(request.getPostMap());

		UploadFile file = request.getFile();
		if (file == null) {
			System.out.println("Upload file is null");
			return;
		}
		System.out.printf("Upload file, name: %s, size: %s, type: %s\n",
				file.getOriginalName(), file.getSize(), file.getContentType());

		Path path = Paths.get("/opt/web/1.rar");
		try (InputStream is = file.getInputStream()) {
			Files.copy(is, path, StandardCopyOption.REPLACE_EXISTING);
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Http(url = "/index2")
	public Object index2(@Multipart("file") UploadFile uploadFile) {
		JSONObject json = new JSONObject();
		json.put("size", uploadFile.getSize());
		json.put("path", uploadFile.getPath().toString());
		json.put("contentType", uploadFile.getContentType());
		System.out.println(">>>>>>>" + uploadFile);
		return json;
	}

}
